'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, TEXT, ENUM, JSON, DECIMAL } = app.Sequelize;

  const Outfit = app.model.define('outfit', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    user_id: {
      type: INTEGER,
      allowNull: false,
      comment: '用户ID',
    },
    name: {
      type: STRING(100),
      allowNull: false,
      comment: '搭配名称',
    },
    description: {
      type: TEXT,
      allowNull: true,
      comment: '搭配描述',
    },
    style: {
      type: ENUM('casual', 'formal', 'business', 'sport', 'party', 'vintage', 'street'),
      allowNull: true,
      comment: '搭配风格',
    },
    occasion: {
      type: JSON,
      allowNull: true,
      comment: '适用场合',
    },
    season: {
      type: ENUM('spring', 'summer', 'autumn', 'winter', 'all'),
      allowNull: true,
      comment: '适用季节',
    },
    weather: {
      type: JSON,
      allowNull: true,
      comment: '适用天气',
    },
    color_scheme: {
      type: JSON,
      allowNull: true,
      comment: '配色方案',
    },
    main_image: {
      type: STRING(255),
      allowNull: true,
      comment: '搭配主图',
    },
    images: {
      type: JSON,
      allowNull: true,
      comment: '搭配图片',
    },
    rating: {
      type: DECIMAL(2, 1),
      allowNull: true,
      comment: '评分(1-5)',
    },
    wear_count: {
      type: INTEGER,
      defaultValue: 0,
      comment: '穿着次数',
    },
    last_worn_date: {
      type: DATE,
      allowNull: true,
      comment: '最后穿着日期',
    },
    is_favorite: {
      type: app.Sequelize.BOOLEAN,
      defaultValue: false,
      comment: '是否收藏',
    },
    is_public: {
      type: app.Sequelize.BOOLEAN,
      defaultValue: false,
      comment: '是否公开',
    },
    tags: {
      type: JSON,
      allowNull: true,
      comment: '标签',
    },
    notes: {
      type: TEXT,
      allowNull: true,
      comment: '备注',
    },
    // 时间戳字段由Sequelize自动管理
  }, {
    tableName: 'outfits',
    comment: '搭配表',
    indexes: [
      {
        fields: ['user_id'],
      },
      {
        fields: ['style'],
      },
      {
        fields: ['season'],
      },
      {
        fields: ['is_favorite'],
      },
      {
        fields: ['is_public'],
      },
    ],
  });

  Outfit.associate = function() {
    // 搭配属于用户
    app.model.Outfit.belongsTo(app.model.User, {
      foreignKey: 'user_id',
      as: 'user',
    });

    // 搭配包含多个衣服
    app.model.Outfit.belongsToMany(app.model.Clothing, {
      through: app.model.OutfitItem,
      foreignKey: 'outfit_id',
      otherKey: 'clothing_id',
      as: 'clothes',
    });

    // 搭配有多个穿着记录
    app.model.Outfit.hasMany(app.model.WearRecord, {
      foreignKey: 'outfit_id',
      as: 'wearRecords',
    });

    // 搭配有多个分享记录
    app.model.Outfit.hasMany(app.model.Share, {
      foreignKey: 'target_id',
      as: 'shares',
      constraints: false,
      // 移除 scope，在查询时手动添加 where 条件
    });
  };

  return Outfit;
};
